import 'dart:convert';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:hbtrans_flutter/beans/home_list_bean.dart';
import 'package:hbtrans_flutter/utils/fluro.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../apis.dart';
import '../../const.dart';
import '../../routes.dart';

class FirstPage extends StatefulWidget {
  @override
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage>
    with AutomaticKeepAliveClientMixin {
  var items = List();
  var loadingDialog;
  HomeListBean homeListBean;
  var banners = List();
  List<NavigationsListBean> navigations = List();

  _getNews() {
    MyDio.getInstance(url: Const.TRANS_SERVER_MY_PATH).get(Apis.getNews,
            (data) {
          if (loadingDialog != null) {
            loadingDialog = null;
            Navigator.pop(context);
          }
          setState(() {
            homeListBean = HomeListBean.fromJson(data);
            _setBanners();
            navigations = homeListBean.navigations;
            items = homeListBean.articles;
          });
        });
  }

  _setBanners() {
    banners.clear();
    for (BannersListBean bean in homeListBean.banners) {
      banners.add(Image.network(
        bean.pic,
        fit: BoxFit.fill,
      ));
    }
  }

  _setTitle() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('title', 'hahahahahah');
    await prefs.setString('name', '123456');
  }

  _setNavigations() {
    return List.generate(
      navigations.length,
          (int index) =>
          GestureDetector(
              onTap: () {
                MyDio.getInstance().clearInstance();
                var name = navigations[index].levelName.split('>')[1];
                if (name == '行政管理') {
                  String route = '${Routes.login}';
                  Routes.router.navigateTo(context, route,
                      replace: false, transition: TransitionType.fadeIn);
                } else if (name == '学时查询') {
                  String route = '${Routes.classLogin}';
                  Routes.router.navigateTo(context, route,
                      replace: false, transition: TransitionType.fadeIn);
                } else if (name == '学车报名') {
                  String route = '${Routes.carEnroll}';
                  Routes.router.navigateTo(context, route,
                      replace: false, transition: TransitionType.fadeIn);
                } else if (name == '在线学习') {
                  String route = '${Routes.videoLearn}';
                  Routes.router.navigateTo(context, route,
                      replace: false, transition: TransitionType.fadeIn);
                } else {
                  var title = jsonEncode(Utf8Encoder().convert(name));
                  var url = jsonEncode(
                      Utf8Encoder().convert(navigations[index].redirectUrl));
                  String route = '${Routes.webView}?title=$title&url=$url';
                  Routes.router.navigateTo(context, route,
                      replace: false, transition: TransitionType.fadeIn);
                }
              },
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Image.network(
                      navigations[index].pic,
                      height: 52,
                    ),
                    SizedBox(
                      height: 4,
                    ),
                    Text(
                      navigations[index].levelName.split('>')[1],
                      style: TextStyle(fontSize: 10, color: Colors.black),
                    )
                  ],
                ),
              )),
    );
  }

  _buildGrid(int i, var retio) {
    return GridView.count(
      // 禁止滚动
      physics: new NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      childAspectRatio: retio,
      //横轴数量 这里的横轴就是x轴 因为方向是垂直的时候 主轴是垂直的
      crossAxisCount: i,
      padding: const EdgeInsets.all(0),
      //主轴间隔
      mainAxisSpacing: 2,
      //横轴间隔
      crossAxisSpacing: 2,
      children: _setNavigations(),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getNews();
    _setTitle();
  }

  @override
  void dispose() {
    super.dispose();
    MyDio.getInstance().clearInstance();
  }

  Future<Null> _onRefresh() async {
    await _getNews();
    return;
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _onRefresh,
      child: ListView(
        children: <Widget>[
          SizedBox(
            height: 200,
            child: Swiper(//轮播组件
              itemBuilder: (BuildContext context, int index) {
                return banners[index];
              },
              itemCount: banners.length,
              pagination: SwiperPagination(
                  builder: DotSwiperPaginationBuilder(
                    color: Colors.black54,
                    activeColor: Colors.white,
                  )),
              control: SwiperControl(),
              scrollDirection: Axis.horizontal,
              autoplay: true,
              onTap: (index) => print('点击了第$index个'),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(10),
            child: _buildGrid(4, 1 / 1),
          ),
          Column(
            children: _doWidgets(),
          )
        ],
      ),
    );
  }

  List<Widget> _doWidgets() {
    List<Widget> listTitles = List();
    for (var i = 0; i < items.length; i++) {
      listTitles.add(buildListItem(context, items[i]));
    }
    return listTitles;
  }

  Widget buildListItem(BuildContext context, ArticlesListBean bean) {
    return GestureDetector(
      onTap: () {
        String route = '${Routes.articleDetail}?articleId=${bean.id}';

        Routes.router.navigateTo(context, route,
            replace: false, transition: TransitionType.fadeIn);
      },
      child: SizedBox(
        height: 80,
        width: 390,
        child: Card(
          elevation: 0,
          color: Colors.white,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 6),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                SizedBox(
                  width: 206,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        bean.title,
                        maxLines: 2,
                        softWrap: true,
                        style: TextStyle(
                            fontSize: 16, color: const Color(0xff4A4A4A)),
                      ),
                      Text(
                        bean.createTime,
                        style: TextStyle(
                            fontSize: 12, color: const Color(0xffB2B2B2)),
                      )
                    ],
                  ),
                ),
                Image.network(
                  bean.headPic,
                  height: 60,
                  width: 80,
                  fit: BoxFit.fill,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
